package com.ruoyi.project.mahjong.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.hutool.core.util.ObjectUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ruoyi.common.exception.BaseException;
import com.ruoyi.common.utils.RecordEntityUtil;
import com.ruoyi.framework.redis.RedisCache;
import com.ruoyi.project.mahjong.domain.*;
import com.ruoyi.project.mahjong.domain.dto.DeskMemberDto;
import com.ruoyi.project.mahjong.domain.enu.*;
import com.ruoyi.project.mahjong.domain.uyil.MemberLogUtil;
import com.ruoyi.project.mahjong.domain.vo.ProductJsonVo;
import com.ruoyi.project.mahjong.mapper.TIntegralMapper;
import com.ruoyi.project.mahjong.mapper.TRecordMapper;
import com.ruoyi.project.mahjong.service.ICommodityService;
import com.ruoyi.project.mahjong.service.ITMemberLogService;
import com.ruoyi.project.mahjong.service.ITMemberService;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.mahjong.mapper.TOpenMoneyMapper;
import com.ruoyi.project.mahjong.service.ITOpenMoneyService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 会员开桌中商品消费Service业务层处理
 *
 * @author ruoyi
 * @date 2023-10-10
 */
@Service
public class TOpenMoneyServiceImpl implements ITOpenMoneyService {
    @Autowired
    private ITMemberLogService tMemberLogService;
    @Autowired
    private TOpenMoneyMapper tOpenMoneyMapper;
    @Autowired
    private ICommodityService commodityService;
    @Autowired
    private TRecordMapper tRecordMapper;
    @Autowired
    private TIntegralMapper integralMapper;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ITMemberService itMemberService;

    /**
     * 查询会员开桌中商品消费
     *
     * @param id 会员开桌中商品消费ID
     * @return 会员开桌中商品消费
     */
    @Override
    public TOpenMoney selectTOpenMoneyById(Long id) {
        return tOpenMoneyMapper.selectTOpenMoneyById(id);
    }

    /**
     * 查询会员开桌中商品消费列表
     *
     * @param tOpenMoney 会员开桌中商品消费
     * @return 会员开桌中商品消费
     */
    @Override
    public List<TOpenMoney> selectTOpenMoneyList(TOpenMoney tOpenMoney) {
        return tOpenMoneyMapper.selectTOpenMoneyList(tOpenMoney);
    }

    /**
     * 新增会员开桌中商品消费
     *
     * @param tOpenMoney 会员开桌中商品消费
     * @return 结果
     */
    @Override
    @Transactional
    public int insertTOpenMoney(TOpenMoney tOpenMoney) {
        TIntegral tIntegrals = integralMapper.selectCostGiveIntegral(tOpenMoney.getShopId());
        Long jbid = redisCache.getCacheObject(tOpenMoney.getShopId() + tOpenMoney.getStaffId().toString());
//        if (ObjectUtil.isNull(tOpenMoney.getPayType())) {
//            throw new BaseException("请选择支付方式");
//        }
        if (jbid == null) {
            throw new BaseException("当前账号店员未点击上班操作");
        }
        if (ObjectUtil.isNotEmpty(tOpenMoney.getJsonVo()) && tOpenMoney.getBuyType().equals("1")) {
            List<ProductJsonVo> jsonVo = tOpenMoney.getJsonVo();
            List<Long> ids = new ArrayList<>();
            for (ProductJsonVo andNumber : jsonVo) {
                ids.add(Long.valueOf(andNumber.getProductId()));
            }
            List<Commodity> productList = tOpenMoneyMapper.selectProductInfoByIds(ids);
            if (ObjectUtil.isEmpty(productList)) {
                throw new BaseException("未查询到该商品信息");
            }
            int intergral = 0;
            for (ProductJsonVo andNumber : jsonVo) {
                TOpenMoney tOpenMoney1 = new TOpenMoney();
                Long productId = Long.valueOf(andNumber.getProductId());
                for (Commodity commodity : productList) {
                    if (commodity.getId().equals(productId)) {
                        BigDecimal price = new BigDecimal(commodity.getPrice());
                        BigDecimal buyNumber = new BigDecimal(andNumber.getBuyNumber());
                        BigDecimal costMoney = buyNumber.multiply(price).setScale(2);
                        tOpenMoney1.setProductId(productId);
                        tOpenMoney1.setBuyNumber(Long.valueOf(andNumber.getBuyNumber()));
                        tOpenMoney1.setMoney(costMoney);
                        tOpenMoney1.setStaffId(tOpenMoney.getStaffId());
                        tOpenMoney1.setMemberId(tOpenMoney.getMemberId());
                        tOpenMoney1.setProductName(commodity.getCommodityName());
                        tOpenMoney1.setBuyTime(new Date());
                        tOpenMoney1.setOrderNumber(tOpenMoney.getOrderNumber());
                        tOpenMoney1.setBak1(tOpenMoney.getShopId().toString());
                        tOpenMoneyMapper.insertTOpenMoney(tOpenMoney1);
//                        if (ObjectUtil.isNotNull(tIntegrals)) {
//                            intergral = countGiveIntergrals(tIntegrals, costMoney);
//                        }
//                        if (ObjectUtil.isNotEmpty(tOpenMoney.getPayType()) && tOpenMoney.getPayType() == 3l) {
//                            Integer i = itMemberService.updateTMemberProductCostMoney(costMoney, tOpenMoney.getMemberId(), intergral);
//                            if (i == 0) {
//                                throw new BaseException("会员余额可能不够");
//                            }
//                        }
                        //添加消费流水和日志
//                        recordLog(tOpenMoney,jbid,commodity,andNumber,costMoney,intergral);

                    }
                }
            }
            return 1;
        } else if (tOpenMoney.getBuyType().equals("2")) {//店员代买商品分支
            List<ProductJsonVo> jsonVo = tOpenMoney.getJsonVo();
            for (ProductJsonVo vo : jsonVo) {
                TOpenMoney tOpenMoney1 = new TOpenMoney();
                tOpenMoney1.setProductName(vo.getProductName());
                tOpenMoney1.setBuyNumber(Long.valueOf(vo.getBuyNumber()));
                tOpenMoney1.setMoney(new BigDecimal(vo.getMoney()));
                tOpenMoney1.setMemberId(tOpenMoney.getMemberId());
                tOpenMoney1.setBuyTime(new Date());
                tOpenMoney1.setOrderNumber(tOpenMoney.getOrderNumber());
                tOpenMoney1.setStaffId(tOpenMoney.getStaffId());
                tOpenMoneyMapper.insertTOpenMoney(tOpenMoney1);
                int intergral = 0;
                if (ObjectUtil.isNotNull(tIntegrals)) {
                    intergral = countGiveIntergrals(tIntegrals, new BigDecimal(vo.getMoney()));
                }
                if (jbid == null) {
                    throw new BaseException("当前账号店员未点击上班操作");
                }


                //添加消费流水和日志
                recordLog(tOpenMoney,vo,jbid,intergral);

            }

            return 1;
        } else {
            throw new BaseException("未选择商品信息");
        }


    }

    /**
     * 增肌消费日志
     * @param tOpenMoney
     * @param vo
     * @param jbid
     * @param intergral
     */
    private void recordLog(TOpenMoney tOpenMoney, ProductJsonVo vo, Long jbid, int intergral) {
        //       添加商品消费流水
        TRecord t = RecordEntityUtil.recordEntity(
                tOpenMoney.getOrderNumber(),
                jbid.toString(),
                tOpenMoney.getStaffId(),
                tOpenMoney.getMemberId(),
                tOpenMoney.getShopId(),
                null,
                null,
                CostType.PRODUCT.getValue(),
                tOpenMoney.getCostTable(),
                ShopIncomeType.INCOME.getValue(),
                null,
                Long.valueOf(vo.getBuyNumber()),
                null,
                Double.valueOf(vo.getMoney()),
                null,
                Double.valueOf(vo.getMoney()),
                CheckoutType.OK.getValue(),
                CheckoutType.NO_REFUND.getValue(),
                null,
                new Date(),
                String.valueOf(intergral),
                null,
                null,
                null,
                tOpenMoney.getRoomId(),
                new Date(),
                tOpenMoney.getStaffId().toString()
        );
        int i = tRecordMapper.insertTRecord(t);
        TMember tMember = itMemberService.selectTMemberById(tOpenMoney.getMemberId());
        TMemberLog tMemberLog = MemberLogUtil.insertMemberLog(
                tOpenMoney.getShopId(),
                tOpenMoney.getStaffId(),
                tOpenMoney.getMemberId(),
                String.valueOf(intergral),
                null,
                null,
                vo.getMoney(),
                MemberLogType.XF.getValue(),
                "商品消费:"+ vo.getMoney()+",商品为:"+vo.getProductName() + ",余额:" +tMember.getMoney(),
                null,
                tMember.getMoney()
        );
        tMemberLogService.insertTMemberLog(tMemberLog);
        /*if(intergral!=0){
            TMemberLog intergralLog = MemberLogUtil.insertMemberLog(tOpenMoney.getShopId(), tOpenMoney.getStaffId(),
                    tOpenMoney.getMemberId(),
                    String.valueOf(intergral),
                    null,
                    null
                    ,
                    null, MemberLogType.JF.getValue(),"进行了商品消费，消费金额为："+ vo.getMoney()+"赠送了积分：积分金额为："+intergral,null

            );
            tMemberLogService.insertTMemberLog(intergralLog);
        }*/
    }

    /**
     * 增加消费日志
     * @param tOpenMoney
     * @param jbid
     * @param commodity
     * @param andNumber
     * @param costMoney
     * @param intergral
     */
    private void recordLog(TOpenMoney tOpenMoney, Long jbid, Commodity commodity, ProductJsonVo andNumber, BigDecimal costMoney, int intergral) {

        //       添加商品消费流水
        TRecord t = RecordEntityUtil.recordEntity(
                tOpenMoney.getOrderNumber(),
                jbid.toString(),
                tOpenMoney.getStaffId(),
                tOpenMoney.getMemberId(),
                tOpenMoney.getShopId(),
                null,
                tOpenMoney.getPayType().toString(),
                CostType.PRODUCT.getValue(),
                tOpenMoney.getCostTable(),
                ShopIncomeType.INCOME.getValue(),
                null,
                Long.valueOf(andNumber.getBuyNumber()),
                null,
                Double.valueOf(costMoney.toString()),
                null,
                Double.valueOf(costMoney.toString()),
                CheckoutType.OK.getValue(),
                CheckoutType.NO_REFUND.getValue(),
                null,
                new Date(),
                String.valueOf(intergral),
                null,
                commodity.getId().toString(),
                null,
                tOpenMoney.getRoomId(),
                new Date(),
                tOpenMoney.getStaffId().toString()
        );
        tRecordMapper.insertTRecord(t);
        TMember tMember = itMemberService.selectTMemberById(tOpenMoney.getMemberId());
        TMemberLog tMemberLog = MemberLogUtil.insertMemberLog(
                tOpenMoney.getShopId(),
                tOpenMoney.getStaffId(),
                tOpenMoney.getMemberId(),
                String.valueOf(intergral),
                null,
                null,
                costMoney.toString(), MemberLogType.XF.getValue(),
                "商品消费:"+costMoney+",商品:"+commodity.getCommodityName() + ",余额:" + tMember.getMoney(),
                null,
                tMember.getMoney()
        );
        tMemberLogService.insertTMemberLog(tMemberLog);
    }

    /**
     * 根据会员消费金额计算赠送积分
     *
     * @param memberAllCostMoney 会员消费金额
     * @return 返回一共送的积分
     */
    private int countGiveIntergrals(TIntegral integrals, BigDecimal memberAllCostMoney) {
        int giveIntegral = 0;

        BigDecimal costMoney = new BigDecimal(integrals.getCostMoney());
        int i = memberAllCostMoney.compareTo(costMoney);
        if (i == -1) {
            return giveIntegral;
        }
        if (costMoney.intValue() == 0) {
            return giveIntegral;
        }
        giveIntegral = (memberAllCostMoney.divide(costMoney)).multiply(new BigDecimal(integrals.getIntegral())).intValue();
        return giveIntegral;
//            BigDecimal  costMoney = new BigDecimal(integrals.getCostMoney());
//            Long i = Long.valueOf(memberAllCostMoney.compareTo(costMoney));
//            if (i== CompareToStatus.DAYU.getValue()){
//                int i1 = (memberAllCostMoney.divide(costMoney)).multiply(new BigDecimal(integrals.getIntegral())).intValue();
//                giveIntegral=giveIntegral+i1;
//            }
    }

    /**
     * 修改会员开桌中商品消费
     *
     * @param tOpenMoney 会员开桌中商品消费
     * @return 结果
     */
    @Override
    public int updateTOpenMoney(TOpenMoney tOpenMoney) {
        return tOpenMoneyMapper.updateTOpenMoney(tOpenMoney);
    }

    /**
     * 批量删除会员开桌中商品消费
     *
     * @param ids 需要删除的会员开桌中商品消费ID
     * @return 结果
     */
    @Override
    public int deleteTOpenMoneyByIds(Long[] ids) {
        return tOpenMoneyMapper.deleteTOpenMoneyByIds(ids);
    }

    /**
     * 删除会员开桌中商品消费信息
     *
     * @param id 会员开桌中商品消费ID
     * @return 结果
     */
    @Override
    public int deleteTOpenMoneyById(Long id) {
        return tOpenMoneyMapper.deleteTOpenMoneyById(id);
    }

    @Override
    public void deleteByMemberId(DeskMemberDto deskMemberDto) {

    }
}
